package net.xiaoyu233.mitemod.miteite.tileentity;

import net.minecraft.*;
import net.xiaoyu233.mitemod.miteite.item.Items;
import net.xiaoyu233.mitemod.miteite.item.recipe.FusionmineRecipe;
import net.xiaoyu233.mitemod.miteite.item.recipe.FusionmineRecipes;


public class TileEntityFusionmine extends TileEntity implements IWorldInventory {
    private  int ftick = 0;
    private  int Maxtime = 0;
    private  boolean Insynthesis = false; // 初始化为 false
    public boolean isUsing = false;
    private ItemStack[] furnaceItemStacks = new ItemStack[5];
    private FusionmineRecipe currentRecipe;
    private boolean[] consumedItems = new boolean[4]; // 用于标记是否已经消耗了对应的物品
    private Item[] heatItemStack = new Item[]{Item.getItem(Block.coalBlock),Item.coal};

    private  int heat = 0;
    private final int MAX_HEAT = 1200;
    private final int HEAT_DECAY_PER_MINUTE = 40;
    private int decayTimer = 0;


    @Override
    public int[] getSlotsForFace(int i) {
        return new int[0];
    }

    @Override
    public boolean canInsertItem(int i, ItemStack itemStack, int i1) {
        return this.isItemValidForSlot(i, itemStack);
    }

    @Override
    public boolean canExtractItem(int i, ItemStack itemStack, int i1) {
        return false;
    }

    @Override
    public int getSizeInventory() {
        return this.furnaceItemStacks.length;
    }

    @Override
    public ItemStack getStackInSlot(int i) {
        return this.furnaceItemStacks[i];
    }

    @Override
    public ItemStack decrStackSize(int par1, int par2) {
        if (this.furnaceItemStacks[par1] != null) {
            ItemStack var3;

            if (this.furnaceItemStacks[par1].stackSize <= par2) {
                var3 = this.furnaceItemStacks[par1];
                this.furnaceItemStacks[par1] = null;
                return var3;
            } else {
                var3 = this.furnaceItemStacks[par1].splitStack(par2);

                if (this.furnaceItemStacks[par1].stackSize == 0) {
                    this.furnaceItemStacks[par1] = null;
                }

                return var3;
            }
        } else {
            return null;
        }
    }

    public ItemStack increaseStackSize(int par1, int par2) {
        if (this.furnaceItemStacks[par1] != null) {
            ItemStack var3;

            var3 = this.furnaceItemStacks[par1].setStackSize(par2);

            if (this.furnaceItemStacks[par1].stackSize == 64) {
                this.furnaceItemStacks[par1] = null;
            }

            return var3;
        } else {
            return null;
        }
    }


    public ItemStack getStackInSlotOnClosing(int i) {
        if (this.furnaceItemStacks[i] != null) {
            ItemStack var2 = this.furnaceItemStacks[i];
            this.furnaceItemStacks[i] = null;
            return var2;
        } else {
            return null;
        }
    }

    public void readFromNBT(NBTTagCompound par1NBTTagCompound) {
        super.readFromNBT(par1NBTTagCompound);
        NBTTagList var2 = par1NBTTagCompound.getTagList("fusionmineItems");
        this.furnaceItemStacks = new ItemStack[this.getSizeInventory()];

        for (int var3 = 0; var3 < var2.tagCount(); ++var3) {
            NBTTagCompound var4 = (NBTTagCompound) var2.tagAt(var3);
            byte var5 = var4.getByte("fusionmineSlot");

            if (var5 >= 0 && var5 < this.furnaceItemStacks.length) {
                this.furnaceItemStacks[var5] = ItemStack.loadItemStackFromNBT(var4);
            }
        }
    }

    @Override
    public void setInventorySlotContents(int par1, ItemStack par2ItemStack) {
        this.furnaceItemStacks[par1] = par2ItemStack;

        if (par2ItemStack != null && par2ItemStack.stackSize > this.getInventoryStackLimit()) {
            par2ItemStack.stackSize = this.getInventoryStackLimit();
        }
    }

    @Override
    public int getInventoryStackLimit() {
        return 64;
    }

    @Override
    public boolean isUseableByPlayer(EntityPlayer entityPlayer) {
        return this.worldObj.getBlockTileEntity(this.xCoord, this.yCoord, this.zCoord) != this ? false : entityPlayer.getDistanceSq((double) this.xCoord + 0.5D, (double) this.yCoord + 0.5D, (double) this.zCoord + 0.5D) <= 64.0D;
    }

    @Override
    public void openChest() {

    }

    @Override
    public void closeChest() {
        this.ftick = 0;
        this.Maxtime = 0;
        this.currentRecipe = null;
    }

    @Override
    public boolean isItemValidForSlot(int i, ItemStack itemStack) {
        return true;
    }

    @Override
    public void destroyInventory() {
        ItemStack[] item_stacks = this.furnaceItemStacks;
        for (int i = 0; i < item_stacks.length; ++i) {
            item_stacks[i] = null;
        }
    }

    public String getUnlocalizedInvName() {
        return this.getBlockType().getUnlocalizedName() + ".name";
    }

    public void writeToNBT(NBTTagCompound par1NBTTagCompound) {
        super.writeToNBT(par1NBTTagCompound);
        NBTTagList var2 = new NBTTagList();

        for (int var3 = 0; var3 < this.furnaceItemStacks.length; ++var3) {
            if (this.furnaceItemStacks[var3] != null) {
                NBTTagCompound var4 = new NBTTagCompound();
                var4.setByte("fusionmineSlot", (byte) var3);
                this.furnaceItemStacks[var3].writeToNBT(var4);
                var2.appendTag(var4);
            }
        }

        par1NBTTagCompound.setTag("fusionmineItems", var2);
    }

    public void setCurrentRecipe(FusionmineRecipe recipe) {
        this.currentRecipe = recipe;
        this.Maxtime = recipe.getOutputTime();
        this.resetConsumedItems();
        if (currentRecipe == null) {
            System.out.println("没有找到匹配的配方");
        } else {
            System.out.println("当前配方: " + currentRecipe.getOutputItem().getUnlocalizedName());
        }
// 每次设置新配方时重置消耗标记
    }
   private boolean getHeatItem(Item j){
        for (int i = 0;i < heatItemStack.length; i++){
            if (heatItemStack[i] == j){
                return true;
            }
        }
        return false;
   }
    private int getHeatItemint(Item j){
        if (j == Item.getItem(Block.coalBlock)){
            return 100;
        }else if (j == Item.coal) {
            return 10;
        }
        return 0;
    }

    @Override
    public void updateEntity() {
        if (!this.getWorldObj().isRemote) {
            // 1. 处理热量自然衰减（每分钟减少40）
            decayTimer++;
            if (decayTimer >= 1200) { // 1200 ticks = 1分钟
                this.heat = Math.max(0, this.heat - HEAT_DECAY_PER_MINUTE);
                decayTimer = 0;
            }
            // 2. 处理三号槽（索引2）的煤炭块添加热量
            if (this.heat < 1200){
                ItemStack fuelStack = this.getStackInSlot(3);
                if (fuelStack != null && this.getHeatItem(fuelStack.getItem()) && fuelStack.stackSize > 0) {
                    this.heat = Math.min(MAX_HEAT, this.heat + this.getHeatItemint(fuelStack.getItem()));
                    this.decrStackSize(3, 1); // 消耗一个煤炭块
                }
            }
            // 3. 检查合成条件（热量必须≥300）
            if (this.heat < 200) {
                this.ftick = 0;
                this.Insynthesis = false;
                return;
            }
            // 4. 检查是否有匹配的配方
            if (currentRecipe == null) {
                for (FusionmineRecipe recipe : FusionmineRecipes.getAllRecipes()) {
                    if (recipe.matches(new ItemStack[]{this.getStackInSlot(0), this.getStackInSlot(1), this.getStackInSlot(2), this.getStackInSlot(3)})) {
                        this.setCurrentRecipe(recipe);
                        break;
                    }
                }
            }
            if (currentRecipe != null) {
                // 5. 检查输出栏物品是否与当前合成输出物品一致
                ItemStack outputStack = this.getStackInSlot(4);
                if (outputStack != null && outputStack.getItem() != currentRecipe.getOutputItem().getItem()) {
                    return;
                }
                // 6. 检查输出栏是否已满
                if (outputStack != null && outputStack.stackSize > 8) {
                    return;
                }
                if (this.ftick < currentRecipe.getOutputTime()) {
                    this.ftick++;
                    this.Insynthesis = true; // 正在合成
                    if (!consumedItems[0] && this.ftick >= currentRecipe.getOutputTime() * 0.2) {
                        this.consumeItem(0); // 消耗第一个物品
                        consumedItems[0] = true; // 标记为已消耗
                    }
                    if (!consumedItems[1] && this.ftick >= currentRecipe.getOutputTime() * 0.4) {
                        this.consumeItem(1); // 消耗第二个物品
                        consumedItems[1] = true; // 标记为已消耗
                    }
                    if (!consumedItems[2] && this.ftick >= currentRecipe.getOutputTime() * 0.6) {
                        this.consumeItem(2); // 消耗第二个物品
                        consumedItems[2] = true; // 标记为已消耗
                    }
                    if (!consumedItems[3] && this.ftick >= currentRecipe.getOutputTime() * 0.95) {
                        this.consumeItem(3); // 消耗第三个物品
                        consumedItems[3] = true; // 标记为已消耗
                    }
                } else {
                    // 7. 合成完成时扣除热量
                    this.heat = Math.max(0, this.heat -  this.currentRecipe.getoutputheat());
                    this.completefusionmine(currentRecipe.getOutputItem().getItem(), currentRecipe.getOutputAmount());
                    this.getWorldObj().getAsWorldServer().playSoundAtBlock(this.xCoord, this.yCoord, this.zCoord, "random.levelup", 1.0F, 1.0F);
                    this.ftick = 0;
                    this.currentRecipe = null;
                    this.Insynthesis = false; // 合成结束
                    this.resetConsumedItems(); // 重置消耗标记
                }
            }
        }
    }

    private void consumeItem(int slot) {
        if (this.furnaceItemStacks[slot] != null && this.furnaceItemStacks[slot].stackSize > 0) {
            this.decrStackSize(slot, 1); // 消耗一个物品
        }
    }

    private void resetConsumedItems() {
        for (int i = 0; i < consumedItems.length; i++) {
            consumedItems[i] = false; // 重置消耗标记
        }
    }

    public FusionmineRecipe getCurrentRecipe() {
        return this.currentRecipe; // 返回当前配方
    }

    private void completefusionmine(Item item, int outputAmount) {
        ItemStack outputStack = this.getStackInSlot(4);
        if (outputStack == null) {
            // 输出栏为空，直接放入新物品
            this.setInventorySlotContents(4, new ItemStack(item, outputAmount));
        } else if (outputStack.getItem() == item && outputStack.stackSize + outputAmount <= 8) {
            // 输出栏有相同物品且未超过最大叠加数
            outputStack.stackSize += outputAmount;
        }
    }


    // 新增方法：获取当前热量
    public int getHeat() {
        return this.heat;
    }

    public int getFtick() {
        return this.ftick;
    }
    public int getMaxtime() {
        return this.Maxtime;
    }

    public boolean getInsynthesis() {
        return this.Insynthesis;
    }

    public void setFtick(int ftick){
        this.ftick = ftick;
    }
    public void setMaxtime(int maxtime) {
        Maxtime = maxtime;
    }
    public void setHeat(int heat) {
        this.heat = heat;
    }
    public void setInsynthesis(boolean Insynthesis) {
         this.Insynthesis = Insynthesis;
    }

}
